<template xmlns="http://www.w3.org/1999/html">
  <el-tabs type="border-card">
    <el-tab-pane>
      <span slot="label"><i class="el-icon-date"></i>商品基本信息</span>
      {{dataForm}}
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="商品分类">
          <el-select v-model="dataForm.goods.category1Id" placeholder="一级分类">
            <el-option
              v-for="item in categorys1"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category2Id" placeholder="二级分类">
            <el-option
              v-for="item in categorys2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category3Id" placeholder="三级分类">
            <el-option
              v-for="item in categorys3"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          模板id:{{dataForm.goods.typeTemplateId}}
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="商品名称" style="width: 70% ">
          <el-input v-model="dataForm.goods.goodsName" placeholder="商品名称" style="width: 70% "></el-input>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="品牌" style="width: 70% ">
          <el-select v-model="dataForm.goods.brandId" placeholder="品牌" style="width: 70% ">
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="副标题" style="width: 70% ">
          <el-input v-model="dataForm.goods.caption" placeholder="副标题" style="width: 70% "></el-input>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="价格" style="width: 70% ">
          <el-input v-model="dataForm.goods.price" placeholder="价格" style="width: 70% "></el-input>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="商品介绍" style="width: 70% ">
          <el-input type="textarea" v-model="dataForm.goodsDesc.introduction" placeholder="商品介绍" style="width: 70% "></el-input>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="包装列表" style="width: 70% ">
          <el-input type="textarea" v-model="dataForm.goodsDesc.packageList" placeholder="商品介绍" style="width: 70% "></el-input>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="dataForm" label-width="180px">
        <el-form-item label="售后服务" style="width: 70% ">
          <el-input type="textarea" v-model="dataForm.goodsDesc.saleService" placeholder="售后服务" style="width: 70% "></el-input>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="商品图片" name="second">
      <span slot="label"><i class="el-icon-date"></i>商品图片</span>
      <el-button type="success" size="small" plain @click="newUpdate">新建</el-button>
      <el-table
        :data="dataForm.goodsDesc.itemImages"
        style="width: 100%;">
        <el-table-column
          prop="color"
          header-align="center"
          align="center"
          label="颜色">
        </el-table-column>
        <el-table-column>
          header-align="center"
          align="center"
          label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="100px" height="50px">
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="dataForm.goodsDesc.itemImages.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="图片上传" :visible.sync="dialogFormVisible">
        <el-form :model="imageEntity">
          <el-form-item label="图片颜色" label-width="100px">
            <el-input v-model="imageEntity.color" ></el-input>
          </el-form-item>
          <el-form-item label="商品图片" label-width="100px">
            <el-upload
              action=""
              class="upload-demo"
              :file-list="fileList"
              :http-request="uploadFile"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="closeUpload">确 定</el-button>
        </div>
      </el-dialog>
    </el-tab-pane>
    <el-tab-pane label="扩展属性" name="third">
      <span slot="label"><i class="el-icon-date"></i>扩展属性</span>
      <el-table
        :data="dataForm.goodsDesc.customAttributeItems"
        style="width: 100%;">
        <el-table-column
          header-align="center"
          align="center">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.value" placeholder="属性值"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="规格" name="fourth">
      <span slot="label"><i class="el-icon-date"></i>规格</span>
      <el-table
        :data="specificationItems"
        style="width: 100%;">
        <el-table-column align="center" width="200px">
          <template slot-scope="scope">
            <span>{{scope.row.text}}</span>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-checkbox-group v-model="optionList[scope.$index]">
              <el-checkbox :label="option.optionName" v-for="option in scope.row.options" :key="option.id" @change="getOptionList"></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>

      <el-table
        :data="dataForm.items"
        style="width: 100%;">
        <el-table-column align="center" width="200px" :key="key" :label="spec.attributeName" v-for="(spec,key) in dataForm.goodsDesc.specificationItems">
          <template slot-scope="scope">
            {{scope.row.spec[spec.attributeName]}}
          </template>
        </el-table-column>
        <el-table-column label="价格">
          <!--        处理价格-->
          <template slot-scope="scope" >
            <el-input v-model="scope.row.price"/>
          </template>
        </el-table-column>
        <!--        处理数量-->
        <el-table-column label="数量">
          <template slot-scope="scope" >
            <el-input v-model="scope.row.num"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-button type="success" size="small" plain @click="save">保存</el-button>
    <el-button type="warning" size="small" plain>返回列表</el-button>
  </el-tabs>
</template>

<script>
  import item from "../../../../../renren-fast-vue-manager/src/views/modules/manager/item";

  export default {
    data () {
      return {
        dataForm: {
          goods: {
            typeTemplateId: ''
          },
          goodsDesc: {
            itemImages: [],
            customAttributeItems: [],
            specificationItems: []
          },
          items: []
        },
        categorys1: [],   // 一级分类
        categorys2: [],   // 二级分类
        categorys3: [],   // 三级分类
        brandList: [],     // 某个模板的品牌列表
        dialogFormVisible: false,  // 隐藏图片上传弹窗
        imageEntity: {},       // 每次上传的图片
        fileList: [],       // 存放图片文件的数组
        specificationItems: [], // 所有的规格及规格选项
        optionList: [],
        specNames: []      // 所有的规格名称
      }
    },
    created () {
      // 查询一级分类
      this.findCategorys1()
      // 根据修改页面传入的id值得到商品对象
      this.findGoodsById();
    },
    watch: {   // 观察属性值的变化
      // 监听一级分类的变化
      category1Idnew (newId, oldId) {  // 监听一级分类
        console.log('新值', newId, '旧值', oldId)
        // 根据当前的id值得到其下所有的二级分类列表
        this.$http({
          url: this.$http.adornUrl(`/shop/itemCat/findParentById/${newId}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log('data(二级分类):', data)
            this.categorys2 = data.list
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 监听二级分类的变化
      category2Idnew (newId, oldId) {
        console.log('新值', newId, '旧值', oldId)
        // 根据当前的id值得到其下所有的三级级分类列表
        this.$http({
          url: this.$http.adornUrl(`/shop/itemCat/findParentById/${newId}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log('data(三级分类):', data)
            this.categorys3 = data.list
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 监听三级分类的变化
      category3Idnew (newId, oldId) {
        console.log('新值', newId, '旧值', oldId)
        // 根据当前的id值得到其下所有的三级级分类列表
        this.$http({
          url: this.$http.adornUrl(`/shop/itemCat/info/${newId}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log('data(三级分类):', data)
            this.dataForm.goods.typeTemplateId = data.itemCat.typeId
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 监听模板变量的变化，会导致以下功能的改变
      // 品牌列表的改变
      // 模板表的扩展属性
      // 模板表的规格并且将相应规格的选项列表也添加在规格列表中
      typeTemplateIdnew (newId, oldId) {
        console.log('新值', newId, '旧值', oldId)
        // 根据当前的id值得到其下所有的三级级分类列表
        this.$http({
          url: this.$http.adornUrl(`shop/typetemplate/info/${newId}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log('data(模板对象):', data)
            // 得到模板的品牌列表
            this.brandList = JSON.parse(data.typeTemplate.brandIds)
            // 得到模板的扩展属性
            this.dataForm.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems)
            // 得到规格及规格选项列表
            this.$http({
              url: this.$http.adornUrl(`shop/specification/findSpecList/${newId}`),
              method: 'get'
            }).then(({data}) => {
              console.log('data--->spec',data.list)
              // 得到所有规格及规格选项列表
              this.specificationItems = data.list
              // 为规格选项列表赋值
              this.optionList = []
              data.list.forEach(d => {
                this.specNames.push(d.text)
                this.optionList.push([])
              })
            })
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      }
    },
    computed: { // 自动计算属性值变化
      // 计算一级分类变量category1Idnew的变化
      category1Idnew () {     // this.dataForm.goods.category2Id属性值变化，会导致category1Idnew属性的变化
        return this.dataForm.goods.category1Id
      },
      // 计算二级分类变量category2Idnew的变化
      category2Idnew () {     // this.dataForm.goods.category2Id属性值变化，会导致category2Idnew属性的变化
        return this.dataForm.goods.category2Id
      },
      // 计算三级级分类变量category3Idnew的变化
      category3Idnew () {     // this.dataForm.goods.category3Id属性值变化，会导致category3Idnew属性的变化
        return this.dataForm.goods.category3Id
      },
      // 当模板id发生变化的时，会导致typeTemplateIdnew变量的改变
      typeTemplateIdnew () {     // this.dataForm.goods.category3Id属性值变化，会导致category3Idnew属性的变化
        return this.dataForm.goods.typeTemplateId
      }
    },
    methods: {
      // 点击某个规格选项复选框时触发
      getOptionList () {
        console.log("optionList:",this.optionList)
        let specList = []
        for (let i = 0; i < this.optionList.length ; i++) {
          let option = this.optionList[i]
          specList.push({attributeName:this.specNames[i], attributeValue:option})
        }
        this.dataForm.goodsDesc.specificationItems = specList
        // 处理特殊情况：当规格选项一个都没有的时候就从dataForm.goodsDesc.specificationItems中删除它
        this.dataForm.goodsDesc.specificationItems = this.dataForm.goodsDesc.specificationItems.filter(f => {
          return f.attributeValue.length > 0;
        })
        this.createItemList();
        // if( this.dataForm.items.length == 1 ){
        //   this.dataForm.items = []
        // }
      },
      // 根据用户选择规格生成规格的sku商品列表
      createItemList () {
        // 定义默认的sku商品列表
        this.dataForm.items = [{spec:{}, price: 0, num: 9999, status: '0', isDefault: '0'}];
        // 得到用户选择的规格列表
        let item = this.dataForm.goodsDesc.specificationItems
        // 遍历规格列表，根据列表动态生成sku列表
        item.forEach(item => {
          this.dataForm.items = this.createColumn(this.dataForm.items, item.attributeName, item.attributeValue)
        })
      },
      createColumn (items, specName, specValue) {
        // 定义生成的新的sku列表数组
        let skuList = []
        // 遍历传入items，动态的为sku商品赋值
        items.forEach(item => {
          specValue.forEach(value => {
            // 根据旧行克隆出新行
            let newRow = JSON.parse(JSON.stringify(item))
            // 为新行赋值
            newRow.spec[specName]  = value
            // 将新行添加到数组中
            skuList.push(newRow)
          })
        })
        // 返回新的数组
        return skuList;
      },
      // 查询一级分类
      findCategorys1 () {
        this.$http({
          url: this.$http.adornUrl('/shop/itemCat/findItemCat1'),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log('data:', data)
            this.categorys1 = data.list
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 处理图片上传请求
      uploadFile (v) {
        // 组织上传的数据
        let form = new FormData()
        // 添加上传的对象
        form.append('file', v.file)
        // 清空列表
        this.fileList = []
        // 开始上传文件
        this.$http({
          url: this.$http.adornUrl(`/shop/upload`),
          method: 'post',
          headers: {'Content-Type':'multipart/form-data'},
          data: form
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log('data(模板对象):', data)
            this.fileList.push({name:v.raw,url:data.url})
            this.imageEntity.url = data.url
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 关闭文件上传
      closeUpload () {
        this.dialogFormVisible = false // 关闭弹窗
        // 为dataForm.goodsDesc.itemImages赋值
        this.dataForm.goodsDesc.itemImages.push(this.imageEntity)
      },
      // 新的上传
      newUpdate () {
        // 显示对话框
        this.dialogFormVisible = true
        // 清空列表
        this.imageEntity = {}
        // 清空上传文件
        this.fileList = []
      },
      // 保存
      save(){
        let id = this.$route.query.id;
        //1. 将需要添加的数据转换为json串
        this.dataForm.goodsDesc.specificationItems = JSON.stringify(this.dataForm.goodsDesc.specificationItems)
        this.dataForm.goodsDesc.itemImages = JSON.stringify(this.dataForm.goodsDesc.itemImages);
        this.dataForm.goodsDesc.customAttributeItems = JSON.stringify(this.dataForm.goodsDesc.customAttributeItems)
        //2. 转换this.dataForm.items中的每一个spec对象为字会串
        this.dataForm.items.forEach(item=>{
          item.spec = JSON.stringify(item.spec);
        })
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/${id?'update':'save'}`),
          method: `${id?'put':'post'}`,
          data:this.dataForm
        }).then(({data}) => {
          if (data && data.code === 0) {
            //1. 添加成功后将所有数据恢复成默认值
            // this.dataForm.goods = {};
            // this.dataForm.goodsDesc = {customAttributeItems: [],specificationItems: [],itemImages: []};
            // this.dataForm.items = [];
            this.dataForm={goods:{typeTemplateId:''},goodsDesc:{itemImages:[],customAttributeItems:[],specificationItems:[]},items:[]},
              this.specificationItems = []
            this.fileList = []
            this.optionList=[];   //选择的规格选项列表
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      //根据id查询商品
      findGoodsById(){
        //1. 得到修改页面传入的id参数
        let id = this.$route.query.id;
        console.log("id:",id);
        //2. 根据传入的商品id，从后台查询出spu商品、spu商品描述、sku商品列表
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/findGoodsById/${id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("findGoodsById:",data);
            this.dataForm = data.goods;
            this.dataForm.goods.brandId = parseInt(data.goods.goods.brandId);   //要将原来的字符串转换为整数
            //将json串转换为json对象(一定要在监听模板id时，判断是否有查询参数id，如果没有才执行从模板表得到自定义扩展属性)
            this.dataForm.goodsDesc.customAttributeItems = JSON.parse(data.goods.goodsDesc.customAttributeItems);
            this.dataForm.goodsDesc.itemImages = JSON.parse(data.goods.goodsDesc.itemImages);
            this.dataForm.goodsDesc.specificationItems = JSON.parse(data.goods.goodsDesc.specificationItems);
            this.dataForm.items.forEach(item=>{
              item.spec = JSON.parse(item.spec);
            })
            //为this.optionList赋值，就会自动选中
            let items = this.dataForm.goodsDesc.specificationItems
            this.optionList=[]
            for(let i = 0;i < items.length;i++){
              this.optionList[i]=items[i].attributeValue;
            }
            console.log("aaaa--->",this.optionList);
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      }
    }
  }
</script>
